import { createSlice } from "@reduxjs/toolkit";

const tabSlice = createSlice({
  name: "tab",
  initialState: {
    isCollapse: false,
    currentMenu: "/home",
    tabList: [
      {
        path: "/home",
        label: "首页",
      },
    ],
  },
  reducers: {
    collapseMenu: (state) => {
      state.isCollapse = !state.isCollapse;
    },
    selectMenuList: (state, { payload: val }) => {
      if (
        val.label !== "/home" &&
        !state.tabList.some((item) => item.label === val.label)
      ) {
        state.tabList.push(val);
      }
    },
    setCurrentMenu: (state, { payload: val }) => {
      state.currentMenu = val;
    },
    deleteMenu: (state, { payload: { path, index } }) => {
      const length = state.tabList.legnth-1
      // 删除的是选中的,
      // 删除的不是选中
      if(path === state.currentMenu){
        state.currentMenu = state.tabList[index - 1].path;
        state.tabList.splice(index, 1);
      }else {
        state.tabList.splice(index, 1);
        
      }
    },
  },
});

export const { collapseMenu, selectMenuList, setCurrentMenu, deleteMenu } =
  tabSlice.actions;
export default tabSlice.reducer;
